package main.core;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

public class ItemArray extends HashMap<Item, Integer> {
	
	private static final long serialVersionUID = 8269964255921620296L;
	private static ItemArray m_items = new ItemArray();
	
	public static ItemArray getInstance()
	{
		return m_items;
	}
	
	//Add an item
	public void add(Item item)
	{
		this.put(item, new Integer(0));
	}
	
	//Calculate the new prices of all items
	public void calculatePrices()
	{
		int total_items_sold = totalNumberOfItemsSold();
		Set<Map.Entry<Item, Integer>> set = this.entrySet();
		Iterator<Entry<Item, Integer>> it = set.iterator();
		Map.Entry<Item, Integer> cur = null;
		while(it.hasNext())
		{
			cur = it.next();
			Item cur_item = (Item)cur.getKey();
			float old_price = cur_item.current_price();
			//THE formula
			float new_price = old_price + (old_price * (getPercentageItemsSold((int)cur.getValue()) - (1 / (float)total_items_sold))) / Settings.getInstance().price_change_sensibility();
			cur_item.setCurrent_price(new_price);
		}
	}

	//Get percentage of items sold
	public float getPercentageItemsSold(int items_sold)
	{
		return items_sold / (float)totalNumberOfItemsSold();
	}
	
	//Get number of sales of an item
	public int getSalesNumberOfItem(String item)
	{
		Set<Map.Entry<Item, Integer>> set = this.entrySet();
		Iterator<Entry<Item, Integer>> it = set.iterator();
		Map.Entry<Item, Integer> cur = null;
		while(it.hasNext())
		{
			cur = it.next();
			Item cur_item = (Item)cur.getKey();
			if(cur_item.name().equals(item))
				return (int)cur.getValue();
		}
		return -1;
	}

	//Get the total number of items sold
	private int totalNumberOfItemsSold()
	{
		int total_items_sold = 0;
		Set<Map.Entry<Item, Integer>> set = this.entrySet();
		Iterator<Entry<Item, Integer>> it = set.iterator();
		Map.Entry<Item, Integer> cur = null;
		while(it.hasNext())
		{
			cur = it.next();
			total_items_sold += (int)cur.getValue();
		}
		return total_items_sold;
	}

	public void setItems(ArrayList<Item> items) {
		this.clear();
		Iterator<Item> iterator = items.iterator();
		while(iterator.hasNext())
		{
			Item item = iterator.next();
			this.add(item);
		}
	}
}
